package com.bookstore.back.service.impl;

import com.bookstore.back.entity.UserAddress;
import com.bookstore.back.mapper.UserAddressMapper;
import com.bookstore.back.service.UserAddressService;
import com.bookstore.back.util.UserContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * 用户地址服务实现类
 * 
 * @author 程序猿_Ti
 * @since 2025-07-22
 */
@Slf4j
@Service
public class UserAddressServiceImpl implements UserAddressService {

    @Autowired
    private UserAddressMapper userAddressMapper;

    @Autowired
    private UserContextUtil userContextUtil;

    @Override
    public List<UserAddress> getUserAddressList() {
        try {
            // 获取当前登录用户ID
            Long currentUserId = userContextUtil.getCurrentUserId();
            if (currentUserId == null) {
                throw new RuntimeException("未登录或登录已过期");
            }

            // 验证当前用户是否为普通用户
            if (!userContextUtil.isCurrentUserRegular()) {
                throw new RuntimeException("权限不足，只有普通用户可以访问");
            }

            return userAddressMapper.selectByUserId(currentUserId.intValue());
        } catch (Exception e) {
            log.error("获取用户地址列表失败：{}", e.getMessage());
            throw new RuntimeException("获取地址列表失败：" + e.getMessage());
        }
    }

    @Override
    public UserAddress getAddressById(Integer addressId) {
        try {
            // 获取当前登录用户ID
            Long currentUserId = userContextUtil.getCurrentUserId();
            if (currentUserId == null) {
                throw new RuntimeException("未登录或登录已过期");
            }

            // 验证当前用户是否为普通用户
            if (!userContextUtil.isCurrentUserRegular()) {
                throw new RuntimeException("权限不足，只有普通用户可以访问");
            }

            UserAddress address = userAddressMapper.selectById(addressId);
            if (address == null) {
                throw new RuntimeException("地址不存在");
            }

            // 验证地址是否属于当前用户
            if (!address.getUserId().equals(currentUserId.intValue())) {
                throw new RuntimeException("无权访问该地址");
            }

            return address;
        } catch (Exception e) {
            log.error("获取地址详情失败：{}", e.getMessage());
            throw new RuntimeException("获取地址详情失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional
    public boolean addUserAddress(Map<String, Object> addressData) {
        try {
            // 获取当前登录用户ID
            Long currentUserId = userContextUtil.getCurrentUserId();
            if (currentUserId == null) {
                throw new RuntimeException("未登录或登录已过期");
            }

            // 验证当前用户是否为普通用户
            if (!userContextUtil.isCurrentUserRegular()) {
                throw new RuntimeException("权限不足，只有普通用户可以访问");
            }

            UserAddress address = new UserAddress();
            address.setUserId(currentUserId.intValue());
            address.setName((String) addressData.get("name"));
            address.setPhone((String) addressData.get("phone"));
            address.setProvince((String) addressData.get("province"));
            address.setCity((String) addressData.get("city"));
            address.setDistrict((String) addressData.get("district"));
            address.setDetail((String) addressData.get("detail"));
            address.setFullAddress((String) addressData.get("fullAddress"));
            address.setTag((String) addressData.get("tag"));
            
            Boolean isDefault = (Boolean) addressData.get("isDefault");
            if (isDefault == null) {
                isDefault = false;
            }
            address.setIsDefault(isDefault);

            // 如果设置为默认地址，先取消其他默认地址
            if (isDefault) {
                userAddressMapper.cancelAllDefaultByUserId(currentUserId.intValue());
            }

            address.setCreatedAt(LocalDateTime.now());
            address.setUpdatedAt(LocalDateTime.now());

            int result = userAddressMapper.insert(address);
            return result > 0;
        } catch (Exception e) {
            log.error("添加用户地址失败：{}", e.getMessage());
            throw new RuntimeException("添加地址失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional
    public boolean updateUserAddress(Integer addressId, Map<String, Object> addressData) {
        try {
            // 获取当前登录用户ID
            Long currentUserId = userContextUtil.getCurrentUserId();
            if (currentUserId == null) {
                throw new RuntimeException("未登录或登录已过期");
            }

            // 验证当前用户是否为普通用户
            if (!userContextUtil.isCurrentUserRegular()) {
                throw new RuntimeException("权限不足，只有普通用户可以访问");
            }

            UserAddress existingAddress = userAddressMapper.selectById(addressId);
            if (existingAddress == null) {
                throw new RuntimeException("地址不存在");
            }

            // 验证地址是否属于当前用户
            if (!existingAddress.getUserId().equals(currentUserId.intValue())) {
                throw new RuntimeException("无权修改该地址");
            }

            UserAddress address = new UserAddress();
            address.setId(addressId);
            address.setName((String) addressData.get("name"));
            address.setPhone((String) addressData.get("phone"));
            address.setProvince((String) addressData.get("province"));
            address.setCity((String) addressData.get("city"));
            address.setDistrict((String) addressData.get("district"));
            address.setDetail((String) addressData.get("detail"));
            address.setFullAddress((String) addressData.get("fullAddress"));
            address.setTag((String) addressData.get("tag"));
            
            Boolean isDefault = (Boolean) addressData.get("isDefault");
            if (isDefault == null) {
                isDefault = false;
            }
            address.setIsDefault(isDefault);

            // 如果设置为默认地址，先取消其他默认地址
            if (isDefault) {
                userAddressMapper.cancelAllDefaultByUserId(currentUserId.intValue());
            }

            address.setUpdatedAt(LocalDateTime.now());

            int result = userAddressMapper.updateById(address);
            return result > 0;
        } catch (Exception e) {
            log.error("更新用户地址失败：{}", e.getMessage());
            throw new RuntimeException("更新地址失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional
    public boolean deleteUserAddress(Integer addressId) {
        try {
            // 获取当前登录用户ID
            Long currentUserId = userContextUtil.getCurrentUserId();
            if (currentUserId == null) {
                throw new RuntimeException("未登录或登录已过期");
            }

            // 验证当前用户是否为普通用户
            if (!userContextUtil.isCurrentUserRegular()) {
                throw new RuntimeException("权限不足，只有普通用户可以访问");
            }

            UserAddress existingAddress = userAddressMapper.selectById(addressId);
            if (existingAddress == null) {
                throw new RuntimeException("地址不存在");
            }

            // 验证地址是否属于当前用户
            if (!existingAddress.getUserId().equals(currentUserId.intValue())) {
                throw new RuntimeException("无权删除该地址");
            }

            // 检查是否为默认地址且用户还有其他地址
            if (existingAddress.getIsDefault()) {
                int addressCount = userAddressMapper.countByUserId(currentUserId.intValue());
                if (addressCount > 1) {
                    throw new RuntimeException("不能删除默认地址，请先设置其他地址为默认地址");
                }
            }

            int result = userAddressMapper.deleteById(addressId);
            return result > 0;
        } catch (Exception e) {
            log.error("删除用户地址失败：{}", e.getMessage());
            throw new RuntimeException("删除地址失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional
    public boolean setDefaultAddress(Integer addressId) {
        try {
            // 获取当前登录用户ID
            Long currentUserId = userContextUtil.getCurrentUserId();
            if (currentUserId == null) {
                throw new RuntimeException("未登录或登录已过期");
            }

            // 验证当前用户是否为普通用户
            if (!userContextUtil.isCurrentUserRegular()) {
                throw new RuntimeException("权限不足，只有普通用户可以访问");
            }

            UserAddress existingAddress = userAddressMapper.selectById(addressId);
            if (existingAddress == null) {
                throw new RuntimeException("地址不存在");
            }

            // 验证地址是否属于当前用户
            if (!existingAddress.getUserId().equals(currentUserId.intValue())) {
                throw new RuntimeException("无权设置该地址");
            }

            // 先取消所有默认地址
            userAddressMapper.cancelAllDefaultByUserId(currentUserId.intValue());

            // 设置当前地址为默认
            UserAddress address = new UserAddress();
            address.setId(addressId);
            address.setIsDefault(true);
            address.setUpdatedAt(LocalDateTime.now());

            int result = userAddressMapper.updateById(address);
            return result > 0;
        } catch (Exception e) {
            log.error("设置默认地址失败：{}", e.getMessage());
            throw new RuntimeException("设置默认地址失败：" + e.getMessage());
        }
    }

    @Override
    public UserAddress getDefaultAddress() {
        try {
            // 获取当前登录用户ID
            Long currentUserId = userContextUtil.getCurrentUserId();
            if (currentUserId == null) {
                throw new RuntimeException("未登录或登录已过期");
            }

            // 验证当前用户是否为普通用户
            if (!userContextUtil.isCurrentUserRegular()) {
                throw new RuntimeException("权限不足，只有普通用户可以访问");
            }

            return userAddressMapper.selectDefaultByUserId(currentUserId.intValue());
        } catch (Exception e) {
            log.error("获取默认地址失败：{}", e.getMessage());
            throw new RuntimeException("获取默认地址失败：" + e.getMessage());
        }
    }
}
